package com.miracle.yuanshen;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

// https://www.jb51.net/article/192335.htm
// https://zhuanlan.zhihu.com/p/511851027
public class SmsInterceptReceiver extends BroadcastReceiver {
    private final String TAG = "SmsRec";

    private static final String SMS_EXTRA_NAME ="pdus";

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"收到一个广播~", Toast.LENGTH_SHORT).show();
        // TODO Auto-generated method stub
        String message = "";

        Log.e(TAG, "free message " );

        Bundle extras = intent.getExtras();
        if ( extras != null ) {
            try {
                Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
                ContentResolver contentResolver = context.getContentResolver();

                Log.e(TAG, "free message " );
                for ( int i = 0; i < smsExtra.length; ++i ) {
                    SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);

                    String body = sms.getMessageBody().toString();
                    message += body;
                }


                Log.e(TAG, "free message : " + message);

            } catch (Exception e) {
                // TODO: handle exception
                Log.e(TAG, e.getMessage());
            }
        }

    }

    // @Override
    // public void onReceive(Context context, Intent intent) {
    //
    // }
}
